package servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;

import org.bson.Document;
import org.bson.types.ObjectId;
import org.json.JSONArray;

import com.mongodb.client.MongoCursor;
import com.mongodb.util.JSON;

import mongo.CourseClass;
import mongo.Task;
import mongo.TeachingMaterialsTemplate;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@WebServlet(description = "taskServletProcess", urlPatterns = { "/manager/task/taskServlet" })
public class taskServlet extends HttpServlet{
	private Task Task = new Task();
	private CourseClass CourseClass = new CourseClass();
	private TeachingMaterialsTemplate TeachingMaterialsTemplate = new TeachingMaterialsTemplate();
	
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		this.doPost(request, response);
	}
	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
	    response.setContentType("text/html;charset=UTF-8");
		
		String method = request.getParameter("method");
		if(method.equals("add")){
			this.add(request, response);
		}else if(method.equals("getCourseClass")) {
			this.getCourseClass(request, response);
		}else if(method.equals("delete")){
			this.delete(request, response);
		}else if(method.equals("list")){
			this.list(request, response);
		}else{
//			request.getRequestDispatcher("404.jsp").forward(request, response); 添加错误页面
		}
	
	}
	
	public void getCourseClass(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("application/text; charset=utf-8");
	    PrintWriter out = response.getWriter();
		String teachercode = request.getParameter("teachercode");
		ArrayList<Document> result = CourseClass.listByTeachercode(teachercode);
		JSONArray jsonArray = new JSONArray();
		for(int i=0;i<result.size();i++){
			jsonArray.put(JSON.parse(result.get(i).toJson()));
		}
		 try {
			 out.write(String.valueOf(jsonArray));
		} catch (Exception e) {
			 e.printStackTrace();
		}finally{
			out.close();
		}
	}
	
	public void add(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		Boolean result = null ;
		HttpSession session = request.getSession();
		try{
			    Document yearSemester = (Document)session.getAttribute("yearSemester");
			    if(yearSemester==null){
			    	yearSemester = new Document();
			    	yearSemester.append("year", "未设置").append("semester", "未设置");
			    }
				String name = request.getParameter("name");
				String content = request.getParameter("content");
				String teachercode = request.getParameter("teachercode");
				String teachername = request.getParameter("teachername");
				String courseclassname = request.getParameter("courseclassname");
				String coursecode = request.getParameter("coursecode");
				String templatename = request.getParameter("templatename");
				ObjectId templateid = new ObjectId(request.getParameter("templateid"));
				Document template = TeachingMaterialsTemplate.findByid(templateid);
				String templatefiledir = template.getString("fileDir");
				Document newDocument = new Document("name",name).
						append("content",content).
						append("teachercode", teachercode).
						append("teachername", teachername).
						append("courseclassname", courseclassname).
						append("coursecode", coursecode).
						append("templatename", templatename).
						append("templatefiledir", templatefiledir).
						append("templateid", templateid).
						append("isfinish", false).
						append("yearsemester", yearSemester.getString("year")+"学年 ，"+yearSemester.getString("semester")+"学期").
						append("createtime", new Date()).
						append("uploadfilename", null).
						append("uploadfiledir", null);
				System.out.println(newDocument);
					result = Task.add(newDocument);
					if(result)
						this.list(request, response);
			//TODO针对返回结果和所属模块，返回到相对应的页面
		}catch(Exception e){
            System.err.println( e.getClass().getName() + ": " + e.getMessage() );
            //TODO发生异常,跳转到对应页面
        }
		
	}
	
	public void delete(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
        try {
    		ObjectId _id = new ObjectId(request.getParameter("_id"));
    		Boolean result = Task.delete(_id);
    		if(result)
				this.list(request, response);
    		//TODO针对返回结果和所属模块，返回到相对应的页面  
        }catch(Exception e){
            System.err.println( e.getClass().getName() + ": " + e.getMessage() );
          //TODO发生异常,跳转到对应页面
        }
	}
	
	
	public void list(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
        try {
    		MongoCursor<Document> result = Task.list();
    		request.setAttribute("result", result);
    	    request.getRequestDispatcher("taskList.jsp").forward(request, response);
    		//response.sendRedirect("departList.jsp");
    		//TODO针对所属模块，返回到相对应的页面   
        }catch(Exception e){
            System.err.println( e.getClass().getName() + ": " + e.getMessage() );
          //TODO发生异常,跳转到对应页面
        }

	}
	
}
